import axios from 'axios'
import qs from 'qs'
import router from '@/router/index'
import { Notify } from 'vant'
import codeConfig from '@/utils/codeConfig'

const $axios = axios.create({
  // withCredentials: true, // 跨域时是否携带cookie 前端配置为true，后端设置Access-Control-Allow-Origin不能为 " * ",必须是你的源地址啊
  baseURL: process.env.VUE_APP_BASE_API, // api的 base_url
  timeout: 10000, // 请求超时
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

// request拦截器
$axios.interceptors.request.use(
  config => {
    const token = ''
    if (token) {
      config.headers['X-Token'] = token
    }
    //POST传参序列化
    if (config.method === 'post') {
      config.data = qs.stringify(config.data);
    }
    return config
  },
  error => {
    Promise.reject(error)
  }
)

// response 拦截器
$axios.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === codeConfig.HTTP_CODE.SUCCESS) {
      return res
    } else {
      if (res.code === '没有登录') {
        router.push({name: 'login'})
      }
      Notify({
        type: 'danger',
        message: res.msg
      })
      return false
    }
  },
  error => {
    Notify({
      type: 'danger',
      message: '网络错误'
    })
    return Promise.reject(error)
  }
)

export default $axios